<template>
  <div class="service-request-panel">
    <div class="panel-header">
      <h2>服务申请管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshServices">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button type="warning" @click="loadUrgentServices">
          <el-icon><Warning /></el-icon>
          紧急申请
        </el-button>
      </div>
    </div>
    
    <!-- 筛选器 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="statusFilter" placeholder="按状态筛选" @change="filterServices">
            <el-option label="全部" value="" />
            <el-option label="待处理" value="PENDING" />
            <el-option label="处理中" value="IN_PROGRESS" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="urgencyFilter" placeholder="按紧急程度筛选" @change="filterServices">
            <el-option label="全部" value="" />
            <el-option label="一般" value="GENERAL" />
            <el-option label="紧急" value="URGENT" />
            <el-option label="非常紧急" value="VERY_URGENT" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input v-model="searchKeyword" placeholder="搜索联系人/电话" @input="filterServices">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button @click="clearFilters">清除筛选</el-button>
        </el-col>
      </el-row>
    </div>
    
    <el-table :data="filteredServices" v-loading="loadingServices" style="width: 100%" row-key="id">
      <el-table-column prop="id" label="申请ID" width="80" />
      <el-table-column prop="userId" label="用户ID" width="80" />
      <el-table-column prop="contactPerson" label="联系人" width="100" />
      <el-table-column prop="contactPhone" label="联系电话" width="120" />
      <el-table-column prop="urgencyLevel" label="紧急程度" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row" :type="getUrgencyType(scope.row.urgencyLevel) || 'info'">
            {{ getUrgencyText(scope.row.urgencyLevel) }}
          </el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row" :type="getServiceStatusType(scope.row.status) || 'info'">
            {{ getServiceStatusText(scope.row.status) }}
          </el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="appointmentTime" label="预约时间" width="180" />
      <el-table-column prop="createdAt" label="申请时间" width="180" />
      <el-table-column prop="completedBy" label="完成人" width="100">
        <template #default="scope">
          <span v-if="scope.row && scope.row.completedBy">
            {{ safeUserCache.get(scope.row.completedBy) || `用户${scope.row.completedBy}` }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="completedAt" label="完成时间" width="180" />
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button size="small" @click="viewServiceDetail(scope.row)">详情</el-button>
          <el-button 
            size="small" 
            type="primary" 
            @click="startService(scope.row)"
            v-if="scope.row && scope.row.status === 'PENDING'"
          >
            开始处理
          </el-button>
          <el-button 
            size="small" 
            type="success" 
            @click="completeService(scope.row)"
            v-if="scope.row && scope.row.status === 'IN_PROGRESS'"
          >
            完成
          </el-button>
          <el-button 
            size="small" 
            type="warning" 
            @click="cancelService(scope.row)"
            v-if="scope.row && scope.row.status === 'PENDING'"
          >
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 服务详情对话框 -->
    <el-dialog v-model="serviceDetailDialogVisible" title="服务申请详情" width="600px">
      <div v-if="selectedService" class="service-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请ID">{{ selectedService.id }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ selectedService.userId }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ selectedService.contactPerson }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedService.contactPhone }}</el-descriptions-item>
          <el-descriptions-item label="服务地址" :span="2">{{ selectedService.serviceAddress }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ selectedService.appointmentTime }}</el-descriptions-item>
          <el-descriptions-item label="紧急程度">{{ getUrgencyText(selectedService.urgencyLevel) }}</el-descriptions-item>
          <el-descriptions-item label="设备信息" :span="2">{{ selectedService.deviceInfo }}</el-descriptions-item>
          <el-descriptions-item label="问题描述" :span="2">{{ selectedService.problemDescription }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ getServiceStatusText(selectedService.status) }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ selectedService.createdAt }}</el-descriptions-item>
          <el-descriptions-item label="完成人" v-if="selectedService.completedBy">
            {{ safeUserCache.get(selectedService.completedBy) || `用户${selectedService.completedBy}` }}
          </el-descriptions-item>
          <el-descriptions-item label="完成时间" v-if="selectedService.completedAt">
            {{ selectedService.completedAt }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="service-actions" v-if="selectedService && (selectedService.status === 'PENDING' || selectedService.status === 'IN_PROGRESS')">
          <el-button type="primary" @click="startService(selectedService)" v-if="selectedService && selectedService.status === 'PENDING'">
            开始处理
          </el-button>
          <el-button type="success" @click="completeService(selectedService)" v-if="selectedService && selectedService.status === 'IN_PROGRESS'">
            完成服务
          </el-button>
          <el-button type="warning" @click="cancelService(selectedService)" v-if="selectedService && selectedService.status === 'PENDING'">
            取消申请
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Warning, Search } from '@element-plus/icons-vue'
import { serviceRequestAPI, userAPI } from '../services/api.js'
import { useAuthStore } from '../store/authStore.js'

export default {
  name: 'ServiceRequestPanel',
  components: {
    Refresh,
    Warning,
    Search
  },
  setup() {
    const loadingServices = ref(false)
    const serviceDetailDialogVisible = ref(false)
    const selectedService = ref(null)
    
    // 认证状态
    const authStore = useAuthStore()
    
    // 筛选器
    const statusFilter = ref('')
    const urgencyFilter = ref('')
    const searchKeyword = ref('')
    
    // 数据
    const serviceRequests = ref([])
    const userCache = ref(new Map()) // 用户信息缓存
    
    // 确保userCache始终可用
    const safeUserCache = computed(() => userCache.value || new Map())
    
    // 筛选后的服务申请
    const filteredServices = computed(() => {
      if (!serviceRequests.value || !Array.isArray(serviceRequests.value)) {
        return []
      }
      
      let filtered = serviceRequests.value
      
      if (statusFilter.value) {
        filtered = filtered.filter(service => service && service.status === statusFilter.value)
      }
      
      if (urgencyFilter.value) {
        filtered = filtered.filter(service => service && service.urgencyLevel === urgencyFilter.value)
      }
      
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        filtered = filtered.filter(service => 
          service && (
            (service.contactPerson && service.contactPerson.toLowerCase().includes(keyword)) ||
            (service.contactPhone && service.contactPhone.includes(keyword))
          )
        )
      }
      
      return filtered
    })
    
    // 获取服务申请
    const loadServiceRequests = async () => {
      loadingServices.value = true
      try {
        const response = await serviceRequestAPI.getAllServiceRequests()
        serviceRequests.value = response.content || response
        
        // 批量加载用户昵称
        await loadUserNicknames(serviceRequests.value)
      } catch (error) {
        ElMessage.error('加载服务申请列表失败：' + error.message)
      } finally {
        loadingServices.value = false
      }
    }
    
    // 获取紧急服务申请
    const loadUrgentServices = async () => {
      loadingServices.value = true
      try {
        const response = await serviceRequestAPI.getUrgentServiceRequests()
        serviceRequests.value = response
        ElMessage.success('已加载紧急服务申请')
      } catch (error) {
        ElMessage.error('加载紧急服务申请失败：' + error.message)
      } finally {
        loadingServices.value = false
      }
    }
    
    // 刷新数据
    const refreshServices = () => loadServiceRequests()
    
    // 筛选服务
    const filterServices = () => {
      // 筛选逻辑在computed中处理
    }
    
    // 清除筛选
    const clearFilters = () => {
      statusFilter.value = ''
      urgencyFilter.value = ''
      searchKeyword.value = ''
    }
    
    // 查看服务详情
    const viewServiceDetail = (service) => {
      selectedService.value = service
      serviceDetailDialogVisible.value = true
    }
    
    // 开始处理服务
    const startService = async (service) => {
      try {
        await serviceRequestAPI.updateServiceStatus(service.id, { status: 'IN_PROGRESS' })
        ElMessage.success('服务申请已开始处理')
        serviceDetailDialogVisible.value = false
        loadServiceRequests()
      } catch (error) {
        ElMessage.error('开始处理失败：' + error.message)
      }
    }
    
    // 完成服务
    const completeService = async (service) => {
      try {
        // 提交完成信息，包含完成人ID
        const completeData = {
          completedBy: authStore.user.value?.id
        }
        await serviceRequestAPI.completeService(service.id, completeData)
        ElMessage.success('服务申请已完成')
        serviceDetailDialogVisible.value = false
        loadServiceRequests()
      } catch (error) {
        ElMessage.error('完成服务失败：' + error.message)
      }
    }
    
    // 取消服务
    const cancelService = async (service) => {
      try {
        await ElMessageBox.confirm('确定要取消这个服务申请吗？', '确认取消', {
          type: 'warning'
        })
        
        await serviceRequestAPI.cancelService(service.id)
        ElMessage.success('服务申请已取消')
        serviceDetailDialogVisible.value = false
        loadServiceRequests()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('取消服务失败：' + error.message)
        }
      }
    }
    
    // 获取紧急程度类型
    const getUrgencyType = (urgency) => {
      if (!urgency) return 'info'
      const typeMap = {
        'GENERAL': 'info',
        'URGENT': 'warning',
        'VERY_URGENT': 'danger'
      }
      return typeMap[urgency] || 'info'
    }
    
    // 获取紧急程度文本
    const getUrgencyText = (urgency) => {
      if (!urgency) return '未知'
      const textMap = {
        'GENERAL': '一般',
        'URGENT': '紧急',
        'VERY_URGENT': '非常紧急'
      }
      return textMap[urgency] || '未知'
    }
    
    // 获取服务状态类型
    const getServiceStatusType = (status) => {
      if (!status) return 'info'
      const typeMap = {
        'PENDING': 'warning',
        'IN_PROGRESS': 'primary',
        'COMPLETED': 'success',
        'CANCELLED': 'danger'
      }
      return typeMap[status] || 'info'
    }
    
    // 获取服务状态文本
    const getServiceStatusText = (status) => {
      if (!status) return '未知'
      const textMap = {
        'PENDING': '待处理',
        'IN_PROGRESS': '处理中',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return textMap[status] || '未知'
    }
    
    // 获取用户昵称
    const getUserNickname = async (userId) => {
      if (!userId) return '未知用户'
      
      // 先检查缓存
      if (safeUserCache.value.has(userId)) {
        return safeUserCache.value.get(userId)
      }
      
      try {
        // 从API获取用户信息
        const userInfo = await userAPI.getUser(userId)
        const nickname = userInfo.nickname || userInfo.username || `用户${userId}`
        
        // 缓存用户信息
        userCache.value.set(userId, nickname)
        return nickname
      } catch (error) {
        console.warn('获取用户信息失败:', error)
        const fallbackNickname = `用户${userId}`
        userCache.value.set(userId, fallbackNickname)
        return fallbackNickname
      }
    }
    
    // 批量获取用户昵称
    const loadUserNicknames = async (serviceRequests) => {
      if (!serviceRequests || !Array.isArray(serviceRequests)) {
        return
      }
      
      const userIds = [...new Set(serviceRequests
        .filter(service => service && service.completedBy)
        .map(service => service.completedBy)
      )]
      
      // 并行获取所有用户信息
      const promises = userIds.map(async (userId) => {
        if (!safeUserCache.value.has(userId)) {
          await getUserNickname(userId)
        }
      })
      
      await Promise.all(promises)
    }
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadServiceRequests()
    })
    
    return {
      loadingServices,
      serviceDetailDialogVisible,
      selectedService,
      statusFilter,
      urgencyFilter,
      searchKeyword,
      serviceRequests,
      userCache,
      safeUserCache,
      filteredServices,
      refreshServices,
      loadUrgentServices,
      filterServices,
      clearFilters,
      viewServiceDetail,
      startService,
      completeService,
      cancelService,
      getUrgencyType,
      getUrgencyText,
      getServiceStatusType,
      getServiceStatusText
    }
  }
}
</script>

<style scoped>
.service-request-panel {
  padding: 20px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.panel-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.service-detail {
  padding: 20px 0;
}

.service-actions {
  margin-top: 20px;
  text-align: center;
}

.service-actions .el-button {
  margin: 0 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .panel-header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .filter-section .el-row {
    flex-direction: column;
  }
  
  .filter-section .el-col {
    margin-bottom: 10px;
  }
}
</style>
